package com.ibm.risk.irmp.base.file.rest;

import com.ibm.risk.irmp.base.file.entity.Attach;
import com.ibm.risk.irmp.base.file.service.AttachService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Date;

@RestController
@CrossOrigin
@RequestMapping("/v2/filestore")
@Slf4j
@Tag(name = "文件存储服务")
public class FileStoreController {

	@Autowired
	AttachService attachService;

	private String tmpPath = System.getProperty("java.io.tmpdir");

	/**
	 * 上传文件
	 *
	 * @return Attach 附件基本信息
	 */
	@RequestMapping(value = "/files", method = RequestMethod.POST)
	@Operation(summary = "上传文件")
	public Attach uploadFile(@RequestParam(value = "file", required = true) MultipartFile file,
			@RequestParam(value = "path", required = true) String path) throws Exception {
		String s = System.getProperty("java.io.tmpdir") + "/" + Thread.currentThread().getName();
		File tmpPath = new File(s);
		if (!tmpPath.exists()) {
			tmpPath.mkdirs();
		}
		String fileName = file.getOriginalFilename();
		String tmpfs = s + "/" + fileName;
		File tmpFile = new File(tmpfs);
		Attach attach = null;
		try {
			file.transferTo(tmpFile);
			attach = attachService.saveAttach(fileName, path, tmpFile);
		} finally {
			tmpFile.delete();
		}
		return attach;
	}

	/**
	 * 下载文件
	 *
	 * @return
	 */
	@GetMapping("/files/{fileId}")
	@Operation(summary = "下载文件")
	public void downloadFile(@PathVariable Long fileId, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String path = tmpPath + "/" + RandomStringUtils.randomAlphanumeric(3)
				+ DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS");
		File file = new File(path);
		Attach attach = attachService.downloadAttach(fileId, new File(path));
		if (attach != null) {
			String fileName = attach.getFileName();

			try (InputStream inputStream = new FileInputStream(file)) {
				String extendFileName = fileName.substring(fileName.lastIndexOf('.'));
				// 动态设置响应类型，根据前台传递文件类型设置响应类型
				response.setContentType(request.getServletContext().getMimeType(extendFileName));
				// 设置响应头,attachment表示以附件的形式下载，inline表示在线打开
				response.setHeader("content-disposition",
						"attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
				// 获取输出流对象（用于写文件）
				OutputStream outputStream = response.getOutputStream();
				IOUtils.copy(inputStream, outputStream);
				outputStream.flush();
			} catch (Exception e) {
				log.error("Error to write file {} to response", fileName, e);
			} finally {
				Files.delete(file.toPath());
			}
		}
	}

	@DeleteMapping("/files/{fileId}")
	@Operation(summary = "删除文件")
	public void deleteFile(@PathVariable Long fileId) throws Exception {
		attachService.deleteAttach(fileId);
	}
}
